// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameEvent from "../../Commons/GameEvent";
import { UINames } from "../../Enums/UIEnum";
import { getTimehms } from "../../GlobalFunction";
import SaveManager from "../../Managers/SaveManager";
import UIManager from "../../Managers/UIManager";
import ShopManager, { ShopEvent } from "../../Models/Shops/ShopManager";
import BaseUI from "../BaseUI";
import ShopItem from "../UIItems/ShopItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ShopUI extends BaseUI {

    @property(cc.Prefab)
    shopItemPrefab: cc.Prefab = null;
    @property(cc.ScrollView)
    scrollview: cc.ScrollView = null;
    @property(cc.Label)
    resetTimeTxt: cc.Label = null;

    leftTime: number = 0;

    protected onLoad(): void {
        var arr = ShopManager.single.getShopTemplateArr();
        for (let i = 0; i < arr.length; i++) {
            var item = cc.instantiate(this.shopItemPrefab);
            item.active = false;
            this.scrollview.content.addChild(item);
        }
    }

    protected onEnable(): void {
        GameEvent.eventNode.on(ShopEvent.BUYGOODS_EVENT, this.onBuyGoods, this);
        ShopManager.single.requestResetShop();
        this.drawShops();
        this.leftTime = 24 * 60 * 60 - (cc.sys.now() - SaveManager.single.userdata.shopResetTime) * 0.001;

    }

    protected onDisable(): void {
        GameEvent.eventNode.off(ShopEvent.BUYGOODS_EVENT, this.onBuyGoods, this);
    }
    onBuyGoods() {
        this.drawShops();
    }

    drawShops() {
        var children = this.scrollview.content.children;
        var arr = ShopManager.single.getShopTemplateArr();

        for (let i = 0; i < arr.length; i++) {
            var element = children[i];
            if (element == null) {
                element = cc.instantiate(this.shopItemPrefab);
                this.scrollview.content.addChild(element);
            }
            element.active = true;
            var itemScript = element.getComponent(ShopItem);
            itemScript.drawItem(arr[i]);
        }
    }

    protected update(dt: number): void {
        if (this.leftTime > 0) {
            this.leftTime -= dt;
            this.resetTimeTxt.string = "刷新时间：" + getTimehms(this.leftTime);
        }
    }

    openRechargeUI() {
        UIManager.single.showUI(UINames.RechargeUI);
    }

    openCardUI() {
        UIManager.single.showUI(UINames.PerpetualCardUI);
    }
}
